package cn.i96688.scanclient.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import cn.i96688.scanclient.bean.PayLog;
import cn.i96688.scanclient.exception.HttpClientException;


/**
 * 
 * http请求工具类
 * 
 *
 */
public class HttpRequest {

//	private static Logger log = Logger.getLogger(HttpRequest.class);
	private final static int ConnectTimeout=8000;//8秒
	private final static int ReadTimeout=20000;

	private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new MiTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
	
	/**
	 * 发送post请求
	 * 
	 * 
	 * @param url
	 *            发送请求的url
	 * 
	 * @param paramsMap
	 *            请求参数
	 * 
	 * @param openId
	 *            关注微信这唯一id
	 * 
	 * @return 发送成功返回true，发送失败返回false
	 * 
	 * @exception 出错抛出异常
	 */
	public static String sendPost(String url, String params) throws Exception {
		if(DebugData.isDebug()) {
			return DebugData.generateData(url, params);
		}
		PrintWriter out = null;
		BufferedReader in = null;


		PayLog.getInstance().addLog("本次请求，URL："+url+"，参数：" + params.toString());
		try {
			URL requestUrl = new URL(url);
			
			trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            //去除https请求时证书不信任
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection(); // 打开和URL之间的连接

			conn.setRequestProperty("accept", "*/*"); // 设置通用的请求属性
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1;HYB_BARCODE_PAY)");
			
			//以下是新加的
			conn.setRequestProperty("contentType", "application/json");
			conn.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (params.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            conn.setRequestMethod("POST");
            //end

			conn.setDoOutput(true); // 发送post请求必须设置
			conn.setDoInput(true);
			conn.setConnectTimeout(ConnectTimeout);
			conn.setReadTimeout(ReadTimeout);

			out = new PrintWriter(conn.getOutputStream()); // 获取 URLConnection
															// 对象的输出流

			out.print(params.toString()); // 发送请求参数

			out.flush(); // 清空输出流的缓冲

			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); // 获取
																							// URLConnection

			StringBuffer result = new StringBuffer(); // 获取Post请求返回的参数
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
			PayLog.getInstance().addLog("post请求返回参数---" + result.toString());
			return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new HttpClientException(e);
		} finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		}
	}
	
	static class MiTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
}
